package com.aote.expression.function;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.browsesoft.PropertiesService;

/**
 * 字符串函数工厂，根据字符串函数名，找到对应的字符串函数处理
 */
public class StringFunctionFactory {
	/**
	 * 缓存的字符串处理函数
	 */
	private Map funcitons;

	/**
	 * 单列
	 */
	private static StringFunctionFactory self = new StringFunctionFactory();

	public static StringFunctionFactory getInstance() {
		return self;
	}

	private StringFunctionFactory() {
		this.funcitons = load();
	}

	/**
	 * 根据属性文件配置，加载函数
	 */
	private Map load() {
		Map result = new HashMap();
		NodeList nl = PropertiesService.getDocument().getElementsByTagName(
				"stringfunction");
		for (int i = 0; i < nl.getLength(); i++) {
			Element e = (Element) nl.item(i);
			// 得到函数名，类名，根据类名构造对象
			String name = e.getAttribute("name");
			String cname = e.getAttribute("class");
			try {
				StringFunction fun = (StringFunction) Class.forName(cname)
						.newInstance();
				result.put(name, fun);
			} catch (InstantiationException e1) {
				throw new RuntimeException("函数不可以实例化：" + cname);
			} catch (IllegalAccessException e1) {
				throw new RuntimeException("函数不可以访问：" + cname);
			} catch (ClassNotFoundException e1) {
				throw new RuntimeException("函数类找不到：" + cname);
			}
		}
		return result;
	}

	/**
	 * 执行函数，函数名对应的类要在属性文件里配置
	 */
	public String invoke(String name, String string, List params) {
		// 得到函数，让函数执行
		StringFunction f = (StringFunction) this.funcitons.get(name);
		String result = f.invoke(string, params); 
		return result;
	}


	/**
	 * 执行多值处理函数
	 */
	public Collection invoke(String name, List params) {
		// 得到函数，让函数执行
		MultiValueFunction f = (MultiValueFunction) this.funcitons.get(name);
		Collection result = f.invoke(params); 
		return result;
	}
}
